<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="物品名称" >
          <el-input v-model="queryParams.goodsName" size="small" style="width: 150px" clearable></el-input>
          
        </el-form-item>
        <el-form-item label="申请单编号" >
          <el-input v-model="queryParams.applyNo" size="small" style="width: 150px" clearable></el-input>
          
        </el-form-item>
        
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-button type="primary" icon="el-icon-plus" size="mini"  @click="handleAdd">创建物品申购申请</el-button>
      </el-row>
  
      <el-table v-loading="loading" :data="deployList">
        <el-table-column label="申请单编号" prop="applyNo" align="center" width="180">
          <template slot-scope="scope">
              <el-link type="primary" @click="handleView(scope.row)" >{{scope.row.applyNo}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="物品名称" align="center" prop="goodsName" :show-overflow-tooltip="true"/>
        <el-table-column label="物品数量" align="center" prop="buyCount" :show-overflow-tooltip="true"/>
        <el-table-column label="物品用途" align="center" prop="purpose" :show-overflow-tooltip="true" />
        <el-table-column label="当前审批人" align="center" prop="currAppprovedBy" />
        <el-table-column label="抄送人" align="center" prop="ccUsers" />
        <el-table-column label="申请单状态" align="center" prop="applyStatus" >
          <template slot-scope="scope">
              <el-tag v-if="scope.row.applyStatus==0" type="info">草稿</el-tag>
              <el-tag v-if="scope.row.applyStatus==1" type="primary">待审批</el-tag>
              <el-tag v-if="scope.row.applyStatus==2" type="danger">审批驳回</el-tag>
              <el-tag v-if="scope.row.applyStatus==3" type="success">审批通过</el-tag>
              <el-tag v-if="scope.row.applyStatus==4" type="danger">已撤销</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交人" align="center" prop="createBy" :show-overflow-tooltip="true"/>
        <el-table-column label="提交时间" align="center" prop="createTime" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              {{parseTime(scope.row.modifyTime)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" >
          <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="撤销申请" placement="top">
                  <el-button
                      size="mini"
                      circle type="warning"
                      icon="el-icon-refresh-left"
                      v-if="scope.row.applyStatus==1"
                      @click="cancelApply(scope.row)"
                  />
              </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <el-dialog title="创建物品申购申请" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
          <el-form :model="goodsBuy" ref="goodsBuy" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="12">
                    <el-form-item label="物品名称" prop="goodsName">
                        <el-input v-model="goodsBuy.goodsName" :disabled="isView"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="物品数量" prop="buyCount">
                        <el-input-number v-model="goodsBuy.buyCount"  :min="1" :max="100" label="描述文字" :disabled="isView"></el-input-number>
                    </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="物品用途" prop="purpose">
                  <el-input v-model="goodsBuy.purpose" type="textarea" :disabled="isView"></el-input>
              </el-form-item>
              <el-row>
                <el-col :span="12" v-if="!isView">
                    <el-form-item label="初审部门" prop="deptIds">
                      <el-cascader style="width:100%;" @change="changeDept" v-model="goodsBuy.deptIds" :disabled="isView"
                        :options="deptOptions"
                        
                        clearable></el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="12" >
                    <el-form-item label="抄送人" prop="ccUsers">
                        <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
                        <el-button type="info" plain size="mini" icon="el-icon-plus" @click="handleCCUser" v-if="!isView">选择抄送人</el-button>
                        <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearCCUser" v-if="ccUserList.length>0 && !isView">清空抄送人</el-button>
                    </el-form-item>
                </el-col>
              </el-row>
              
              
          </el-form>
          <div >
            <approvalHistory :processId="goodsBuy.processId" v-if="goodsBuy.processId && dialogVisible"></approvalHistory>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm" v-if="!isView">提 交</el-button>
              <el-button @click="handleClose">取 消</el-button>
          </div>
      </el-dialog>
  
      <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
        <deptUser @getTaskUser="getApprovedUser" :multiple="false" v-if="dialogVisibleUser"></deptUser>
      </el-dialog>

      <el-dialog :visible.sync="dialogVisibleCCUser" title="选择抄送人员">
        <deptUser @getTaskUser="getCCuser" :multiple="true"  v-if="dialogVisibleCCUser"></deptUser>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getToken } from "@/utils/auth";
  import {pageList,createApply,cancelApply } from "@/api/workflow/goodsBuyApply"
  import { findClassByTeacher} from "@/api/classManage/classInfo";
  import { queryClassStudents } from "@/api/studentInfo/examResultEnter";
  import deptUser from '../../components/userSelect/deptUser.vue'
  import approvalHistory from '../../components/workflow/approvalHistory'
  import { treeselectAll } from "@/api/system/dept";
  
  export default {
    name: "Config",
    components: {
      approvalHistory,
      deptUser
    },
    data() {
      var checkApproved = (rule, value, callback) => {
        console.log(value)
        if (!this.goodsBuy.currApprovedBy || this.goodsBuy.currApprovedBy.length < 1) {
          callback(new Error("请选择审批人！"));
        } else {
          callback();
        }
      };  
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 参数表格数据
        deployList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 类型数据字典
        typeOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          leaveType: null,
          paramKey: undefined,
          paramType: undefined
        },
        dialogVisible:false,
        dialogVisibleUser:false,
        dialogVisibleCCUser:false,
        goodsBuy:{
  
        },
        rules:{
          goodsName:[
              { required: true, message: "请填写物品名称", trigger: "blur"},
            ],
            buyCount:[
              { required: true, message: "请填写物品数量", trigger: "blur"},
             ],
            purpose:[{ required: true, message: "请填写申购原因", trigger: "blur"}],
            deptIds:[{ required: true, message: "请选择初审部门", trigger: "blur"}]

        },
        leaveTypeList:[],
        isView:false,
        deptOptions:[],
        props:{multiple: true},
        ccUserList:[],
        userList:[],
        classList:[],
        students:[]
      };
    },
    computed: {
      headers() {
        return {
          'Authorization': getToken()
        }
      }
    },
    created() {
      this.getList();
      this.getClass()
      this.getTreeselect()
      this.getDicts("leave_type").then(response => {
        this.leaveTypeList = response.data;
      });
  
    },
    methods: {
        
        getSutdentsAndClassName(classIdParam){
            let classItme = this.classList.filter(item => {
                return item.id==classIdParam;
            });
            if(classItme.length>0){
                this.goodsBuy.className = classItme[0].className
            }
            
            queryClassStudents({classId:classIdParam}).then(resp=>{
                this.students = resp.data
            })
        },
        getStudentName(studentId){
            let studentItme = this.students.filter(item=>{
                return item.id==studentId;
            })
            if(studentItme.length>0){
                this.goodsBuy.studentName = studentItme[0].name
            }
            console.log(this.goodsBuy)
        },
      getClass(){//查询当前用户管理的班级
        findClassByTeacher().then(resp=>{
            this.classList = resp.data
        })
      },
      clearUser(){
        this.userList=[]
        this.goodsBuy.currApprovedBy=null
      },
      clearCCUser(){
        this.ccUserList=[]
        this.goodsBuy.currApprovedBy=null
      },
      getApprovedUser(data,isClose){
        this.userList = data
        if(data){
          let ccUser = []
          for(let i=0;i<data.length;i++){
            ccUser.push(data[i].userName)
          }
          this.goodsBuy.currApprovedBy= ccUser.join(',')
          
        }
        this.$refs['goodsBuy'].clearValidate('ccUserList')
        this.dialogVisibleUser = isClose
      },
      getCCuser(data,isClose){
        this.ccUserList = data
        if(data){
          let ccUser = []
          for(let i=0;i<data.length;i++){
            ccUser.push(data[i].userName)
          }
          this.goodsBuy.ccUsers = ccUser.join(',')
          
        }
        this.$refs['goodsBuy'].clearValidate('ccUserList')
        this.dialogVisibleCCUser = isClose
      },
      handleUser(){
        this.dialogVisibleUser = true
      },
      handleCCUser(){
        this.dialogVisibleCCUser = true
      },
      changeDept(item){
        console.log(item)
        this.goodsBuy.deptId = item[item.length-1]
      },
       /** 查询部门下拉树结构 */
       getTreeselect() {
        treeselectAll().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 查询参数列表 */
      getList() {
        this.loading = true;
        pageList(this.queryParams).then(response => {
            this.deployList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          paramName: undefined,
          paramKey: undefined,
          paramValue: undefined,
          paramType: "Y",
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams={
          pageNum: 1,
          pageSize: 10,
          leaveType:null,
          times:null,
          applyNo:null
        }
        this.handleQuery();
      },
      resetForm(){
          this.goodsBuy={
              leaveStartTime:undefined,
              leaveEndTime:undefined,
              leaveTotalTime:undefined,
              leaveType:undefined,
              leaveRemarks:undefined,
          }
      },
      handleView(row){
          this.isView = true
          this.goodsBuy = row
          if(row.ccUsers){
            this.ccUserList = row.ccUsers.split(',').map(item=>{
                return {userName:item}
            })
          }
          
        //   const deptArray = row.approvedDept.split(';')
        //   let approvedDeptArray = []
        //   for(let i=0;i<deptArray.length;i++){
        //     let dataIntAry = deptArray[i].split(',')
        //     approvedDeptArray.push(dataIntAry.map(item=>{
        //       return +item
        //     }))
        //   }
        //   this.goodsBuy.approvedDeptModel = approvedDeptArray
          this.dialogVisible = true
      },
      handleClose(done){
          this.dialogVisible = false
      },
      handleAdd(){
          this.resetForm()
          this.dialogVisible = true
          this.isView = false
          this.ccUserList=[]
      },
      submitForm(){
          console.log(this.goodsBuy)
          this.$refs["goodsBuy"].validate(valid => {
              if(valid){
                  this.goodsBuy.status=1
                  createApply(this.goodsBuy).then(resp=>{
                      this.$message({ message: '提交成功', type: 'success' });
                      this.dialogVisible = false
                      this.getList()
                  })
              }
          })
      },
      cancelApply(row){
          this.$confirm('取消要撤销请假申请吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              const applyData = {
                  processInstanceId: row.processId
              }
              this.loading = true
              cancelApply(applyData).then(resp=>{
                  this.$message({ type: 'success', message: '撤销成功!'});
                  this.getList()
              })
            
          })
      },
      computeDays(){
        this.goodsBuy.leaveStartTime
        this.goodsBuy.leaveEndTime
      },
      compareDate(start,end){ 
              if(start==null||start.length==0||end==null||end.length==0){ 
                  return 0; 
              } 
               
              var arr=start.split("-");  
              var starttime=new Date(arr[0],arr[1],arr[2]);  
              var starttimes=starttime.getTime(); 
               
              var arrs=end.split("-");  
              var endtime=new Date(arrs[0],arrs[1],arrs[2]);  
              var endtimes=endtime.getTime(); 
               
              var intervalTime = endtimes-starttimes;//两个日期相差的毫秒数 一天86400000毫秒 
              var Inter_Days = ((intervalTime).toFixed(2)/86400000)+1;//加1，是让同一天的两个日期返回一天 
               
              return Inter_Days; 
          } 
    }
  };
  </script>
  